<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-form :inline="true" class="demo-form-inline" :disabled="disabled">
      <el-form-item label="一级分类">
        <el-select
          placeholder="请选择一级分类"
          v-model="category1Id"
          @change="category1IdChange"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in category1List"
            :key="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择二级分类"
          v-model="category2Id"
          @change="category2IdChange"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in category2List"
            :key="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择三级分类" v-model="category3Id">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in category3List"
            :key="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, watch } from "vue";

export default defineComponent({
  name: "Category",
});
</script>

<script setup lang="ts">
import useCategoryStore from "@/stores/category";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
const categoryStore = useCategoryStore();

defineProps<{
  disabled: boolean;
}>();

//获取pinia中一级分类的数据
const {
  category1List,
  category1Id,
  category2List,
  category2Id,
  category3List,
  category3Id,
} = storeToRefs(categoryStore);

// category1Id的改变后回调函数
const category1IdChange = () => {
  // 每次当1重选的时候，要把2和3清空掉
  category2List.value = [];
  category2Id.value = null;
  category3List.value = [];
  category3Id.value = null;
  //发送2List的请求
  categoryStore.getCategory2List();
};

//category2Id的改变后回调函数
const category2IdChange = () => {
  //每次当2重选的时候,要把3给清理掉
  category3List.value = [];
  category3Id.value = null;
  //发送2List的请求
  categoryStore.getCategory3List();
};
//初始的时候首先请求一级分类列表
onMounted(() => {
  try {
    categoryStore.getCategory1List();
  } catch (e: any) {
    ElMessage.error(e.message);
  }
});
</script>

<style scoped></style>
